<script setup lang="ts">
    import { useAdmin } from '@/stores/admin' //导入admin状态文件
    import { useToken } from '@/stores/token' //导入token状态文件
    import { ref, inject, type Ref } from 'vue' //引入vue函数
    import type { UploadInstance } from 'element-plus' //导入实例类型
    import { uploadPictureURL, changeAdminAvatar } from '@/api' //引入API函数
    import type { AxiosResponse } from 'axios' //导入response类型
    import { ElMessage } from 'element-plus' //导入消息框

    //执行方法获得adminStore对象
    const adminStore = useAdmin()

    //执行方法获得tokenStore对象
    const tokenStore = useToken()

    //用户头像
    const headImage = inject<Ref>("headImage", ref(""))

    //图片上传地址
    const uploadURL = uploadPictureURL()

    //设置图片上传时请求的头
    const headers = { jwt: tokenStore.token }

    //定义商品上传组件实例
    const uploadRef = ref<UploadInstance>()

    //上传头像
    function submitUpload(){
        uploadRef.value?.submit()
    }

    //图片上传成功后的回调函数
    async function uploadSuccess(response:AxiosResponse){
        //修改管理员头像
        const res = await changeAdminAvatar({ avatar:response.data.savepath })
        if(res.data.errno == 0){
            //修改头像成功
            ElMessage.success(res.data.errmsg)
            //设置显示的头像
            headImage.value = response.data.url
            //设置管理员stores中的头像
            adminStore.admin.avatar = response.data.url
        }
        else{
            //修改头像失败
            ElMessage.error(res.data.errmsg)
        }
        //清空上传组件的已上传文件列表
        uploadRef.value?.clearFiles()
    }
</script>

<template>
    <section class="person_image">
        <div>头像信息</div>
        <div><img :src="headImage" /></div>
        <el-upload ref="uploadRef" :action="uploadURL" :limit="1" :headers="headers" :data="{type:'admin_avatar'}" :auto-upload="false" :on-success="uploadSuccess">
            <template #trigger>
                <div class="image_btn"><el-button type="primary">选择头像</el-button></div>
            </template>
            <template #default>
                <div class="image_btn"><el-button type="success" @click="submitUpload">上传头像</el-button></div>
            </template>
            <template #tip>
                <div class="image_txt">限制上传1个文件，且旧文件会被新文件覆盖</div>
            </template>
        </el-upload>
    </section>
</template>

<style scoped>
    .person_image{
        border:1px solid #E4E7ED;
        border-radius: 5px;
        width:30%;
        box-shadow: 0px 0px 5px 5px #E4E7ED;
        margin:20px;
    }
    .person_image  div:not(:first-child){
        text-align:center;
        margin:5px 0px;
    }
    .person_image > div:first-child{
        font-size:15px;
        text-indent: 15px;
        line-height:50px;
        border-bottom:1px solid #E4E7ED;
    }
    .person_image img{
        width:50px;
        height:50px;
        margin-top:10px;
    }
    .person_image .image_txt{
        color:gray;
        font-size:13px;
    }
</style>
